package cn.mily.user.controller;


import cn.mily.basics.utils.JsonResult;
import cn.mily.user.domain.LoginInfo;
import cn.mily.user.service.ILoginService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private ILoginService service;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 邮箱验证码登录
     * @param loginInfo
     * @return
     */
    @PostMapping("/email")
    public JsonResult loginByEmail(@RequestBody LoginInfo loginInfo){
        try {
            return service.loginByEmail(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(e.getMessage());
        }
    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    @GetMapping("/{token}")
    public String getUserName(@PathVariable String token){
        LoginInfo loginInfo = (LoginInfo)redisTemplate.opsForValue().get(token);
        /* 未进行登录 */
        if(loginInfo==null){
            return null;
        }
        if(!StringUtils.isEmpty(loginInfo.getUsername())){
            return loginInfo.getUsername();
        }
        if (!StringUtils.isEmpty(loginInfo.getEmail())) {
            return loginInfo.getEmail();
        }
        if(!StringUtils.isEmpty(loginInfo.getPhone())){
            return loginInfo.getPhone();
        }
        return null;
    }


    /**
     * 用户登录 + 记住我
     * @param loginInfo 登录信息
     * @return
     */
    @PostMapping
    public JsonResult login(@RequestBody LoginInfo loginInfo){
        try {
            return service.login(loginInfo);
        } catch (Exception e) {
            /*e.printStackTrace();*/
            return new JsonResult(e.getMessage());
        }
    }

}
